from flask import Blueprint
from flask import jsonify
from extensions import db
from models import Attendance
from models import StudentAttendanceSummary
from collections import defaultdict


# 统计并插入数据
def update_attendance_summary():
    # 初始化一个字典，用于统计每个学生的缺席次数
    attendance_summary = defaultdict(lambda: {
        'morning_absent_times': 0,
        'exercise_absent_times': 0,
        'school_over_absent_times': 0,
        'phone_absent_times': 0
    })

    # 从 attendance_records 表中读取数据
    records = Attendance.query.all()

    # 遍历每一行数据
    for record in records:
        # 拆分每个字段中的学生姓名
        morning_absent_list = record.morning_absent.split(',') if record.morning_absent else []
        exercise_absent_list = record.exercise_absent.split(',') if record.exercise_absent else []
        school_over_absent_list = record.school_over_absent.split(',') if record.school_over_absent else []
        phone_absent_list = record.phone_absent.split(',') if record.phone_absent else []

        # 统计每个学生的缺席次数
        for student in morning_absent_list:
            attendance_summary[student]['morning_absent_times'] += 1
        for student in exercise_absent_list:
            attendance_summary[student]['exercise_absent_times'] += 1
        for student in school_over_absent_list:
            attendance_summary[student]['school_over_absent_times'] += 1
        for student in phone_absent_list:
            attendance_summary[student]['phone_absent_times'] += 1

    # 将统计结果插入到 student_attendance_summary 表中
    for student, counts in attendance_summary.items():
        # 查询是否已存在该学生的记录
        summary_record = StudentAttendanceSummary.query.filter_by(stu_name=student).first()
        if summary_record:
            # 如果存在，更新记录
            summary_record.morning_absent_times = counts['morning_absent_times']
            summary_record.exercise_absent_times = counts['exercise_absent_times']
            summary_record.school_over_absent_times = counts['school_over_absent_times']
            summary_record.phone_absent_times = counts['phone_absent_times']
        else:
            # 如果不存在，插入新记录
            new_record = StudentAttendanceSummary(
                stu_name=student,
                morning_absent_times=counts['morning_absent_times'],
                exercise_absent_times=counts['exercise_absent_times'],
                school_over_absent_times=counts['school_over_absent_times'],
                phone_absent_times=counts['phone_absent_times']
            )
            db.session.add(new_record)

    # 提交事务
    db.session.commit()
    print("数据统计并插入成功！")



# 创建蓝图
get_attendance_summary_bp = Blueprint('get_attendance_summary', __name__)
@get_attendance_summary_bp.route('/attendance-summary', methods=['GET'])
def get_attendance_summary():
    print("开始统计考勤数据...")
    update_attendance_summary()
    try:
        # 查询数据库中的所有考勤记录
        records = StudentAttendanceSummary.query.all()
        
        # 将查询结果转换为字典列表
        attendance_records = []
        for record in records:
            attendance_records.append({
                'name': record.stu_name,
                'morning_absent_times': record.morning_absent_times,
                'exercise_absent_times': record.exercise_absent_times,
                'school_over_absent_times': record.school_over_absent_times,
                'phone_absent_times': record.phone_absent_times
            })
        # 返回 JSON 数据
        return jsonify(attendance_records)
    except Exception as e:
        print("出错信息：",e)
        # 返回错误信息
        return jsonify({
            'error': '服务器内部错误',
            'message': str(e)
        }), 500